﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Text;

namespace Vit.Common.Extensions
{
    public static class XElementExtensions
    {
        public static string AttributeValue(this XElement ele, string attributeName, string defaultValue)
        {
            if (ele == null)
                return defaultValue;
            if (ele.Attribute(attributeName) == null)
                return defaultValue;
            return ele.Attribute(attributeName).Value;
        }

        public static T AttributeValue<T>(this XElement ele, string attributeName, T defaultValue)
        {
            if (ele == null)
                return defaultValue;
            if (ele.Attribute(attributeName) == null)
                return defaultValue;
            return ele.Attribute(attributeName).Value.ConvertTo<T>(defaultValue);
        }

        public static string AttributeValue(this XElement ele, string xpath, string attributeName, string defaultValue)
        {
            if (ele == null)
                return defaultValue;
            XElement cele = ele.XPathSelectElement(xpath);
            if (cele == null)
                return defaultValue;
            return cele.AttributeValue(attributeName, defaultValue);
        }

        public static T AttributeValue<T>(this XElement ele, string xpath, string attributeName, T defaultValue)
        {
            if (ele == null)
                return defaultValue;
            XElement cele = ele.XPathSelectElement(xpath);
            if (cele == null)
                return defaultValue;
            return cele.AttributeValue<T>(attributeName, defaultValue);
        }

        public static string ElementValue(this XElement ele, string xpath, string defaultValue)
        {
            if (ele == null)
                return defaultValue;
            XElement cele = ele.XPathSelectElement(xpath);
            if (cele == null)
                return defaultValue;
            return cele.Value;
        }

        public static T ElementValue<T>(this XElement ele, string xpath, T defaultValue)
        {
            if (ele == null)
                return defaultValue;
            XElement cele = ele.XPathSelectElement(xpath);
            if (cele == null)
                return defaultValue;
            return cele.Value.ConvertTo<T>(defaultValue);
        }

        public static Dictionary<string, string> ToDictionay(this XElement ele)
        {
            if (ele == null || ele.HasElements == false)
                return null;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (XElement se in ele.Elements())
            {
                dic.Add(se.Name.LocalName, se.Value);
            }
            return dic;
        }
    }
}
